package de.hwr.sudokuspielehr.timer;

import javax.swing.JLabel;

public class LabelTimerThread extends Thread {

	/**
	 * 
	 */
	private Stopwatch s;

	/**
	 * Label to process.
	 */
	private JLabel label;

	/**
	 * Timer paused?
	 */
	private boolean paused = false;

	/**
	 * 
	 */
	private boolean resumed = false;

	/**
	 * 
	 */
	private long savedSeconds = 0;

	/**
	 * Constructor of timer thread.
	 * 
	 * @param pLabel
	 */
	public LabelTimerThread(JLabel pLabel) {
		label = pLabel;
	}

	@Override
	public void run() {
		s = new Stopwatch();
		s.setStartTime(System.currentTimeMillis());

		while (true) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			if (paused) {
				if (resumed) {
					paused = false;
					s.setStartTime(System.currentTimeMillis());
					resumed = false;
				}
			} else {
				int seconds = (int) ((savedSeconds + s.getMillisSinceStart()) / 1000);
				label.setText(toTimerString(seconds));
				label.updateUI();
			}
		}
	}

	public void pauseTimer() {
		if (!paused) {
			paused = true;
			savedSeconds = savedSeconds + s.getMillisSinceStart();
		}
	}

	public void resumeTimer() {
		if (paused) {
			resumed = true;
		}
	}

	/**
	 * Converts the given Integer to a timer String.
	 * 
	 * @return
	 */
	private String toTimerString(int pNumber) {
		if (pNumber > 60 * 60) {
			return "Viel zu lange!";
		}

		int minutes = pNumber / 60;
		int seconds = pNumber % 60;

		String minutesString = "00";
		String secondsString = "00";

		if (minutes < 10) {
			minutesString = "0" + minutes;
		} else {
			minutesString = minutes + "";
		}

		if (seconds < 10) {
			secondsString = "0" + seconds;
		} else {
			secondsString = seconds + "";
		}

		String displayString = minutesString + ":" + secondsString;

		return displayString;
	}
}
